package com.cdd.servicezhifubao.service.impl;


import com.cdd.servicezhifubao.dao.AccountInfoMapper;
import com.cdd.servicezhifubao.feign.BankCardFeign;
import com.cdd.servicezhifubao.model.AccountInfo;
import com.cdd.servicezhifubao.service.AccountService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @Description TODO
 * @Author: cdd
 * @Date: 2020/7/9 15:09
 * @Version: 1.0
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    AccountInfoMapper accountInfoMapper;

    @Resource
    BankCardFeign bankCardFeign;

    @Override
    public AccountInfo getById(Long id) {
        return accountInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional  // 本地事务
    @GlobalTransactional // 分布式事务
    public int updateAccountById(Integer amount) {
        AccountInfo accountInfo = getById(1L);
        accountInfo.setBalance(accountInfo.getBalance() - amount);
        int flag = accountInfoMapper.updateByPrimaryKeySelective(accountInfo); // 支付宝出账
        Assert.state(flag == 1, "支付宝账户更新失败");

        String rs = bankCardFeign.income(amount);  // 银行卡入账
        Assert.state(!"fallback".equals(rs), "银行卡微服务调用失败");

        return 1;
    }
}
